"""
Description:
Author: 月间
Date: 2024-09-09 22:53:19
LastEditTime: 2025-03-22 14:58:19
LastEditors:
"""

# @Version        : 1.0
# @Update Time    : 2024/9/9 22:53
# @File           : orm.py
# @IDE            : PyCharm
# @Desc           : 文件描述信息
from datetime import datetime
from advanced_alchemy.base import CommonTableAttributes, orm_registry
from sqlalchemy import func, DateTime, Integer, String, inspect
from sqlalchemy.orm import Mapped, mapped_column, DeclarativeBase


class AttrBase:
    """Base for all SQLAlchemy declarative models with the custom UUID primary key ."""

    id: Mapped[int] = mapped_column(primary_key=True, comment="主键ID", sort_order=-1)
    create_by: Mapped[int | None] = mapped_column(
        Integer, nullable=True, default=None, comment="创建者"
    )
    update_by: Mapped[int | None] = mapped_column(
        Integer, nullable=True, default=None, comment="更新者", sort_order=999
    )
    created_at: Mapped[datetime] = mapped_column(
        DateTime, default=func.now(), comment="创建时间", sort_order=999
    )
    updated_at: Mapped[datetime | None] = mapped_column(
        DateTime, default=None, onupdate=func.now(), comment="更新时间", sort_order=999
    )
    deleted_at: Mapped[datetime | None] = mapped_column(
        DateTime, comment="删除时间", sort_order=999
    )
    is_deleted: Mapped[str] = mapped_column(
        String(1), default="0", comment="是否软删除(0:正常，1:删除)", sort_order=999
    )


class AbstractORMModel(AttrBase, CommonTableAttributes, DeclarativeBase):
    """
    公共 ORM 模型，基表

    表配置官方文档：https://docs.sqlalchemy.org/en/20/orm/declarative_tables.html
    支持 Enum 与 Literal 官方文档：https://docs.sqlalchemy.org/en/20/orm/declarative_tables.html#using-python-enum-or-pep-586-literal-types-in-the-type-map
    """  # noqa E501

    registry = orm_registry

    @classmethod
    def get_column_attrs(cls):
        """
        获取模型中除 relationships 外的所有字段名称
        :return:
        """
        mapper = inspect(cls)
        return mapper.column_attrs.keys()

    @classmethod
    def get_attrs(cls) -> list:
        """
        获取模型所有字段名称
        :return:
        """
        mapper = inspect(cls)
        return mapper.attrs.keys()

    @classmethod
    def get_relationships_attrs(cls) -> list:
        """
        获取模型中 relationships 所有字段名称
        :return:
        """
        mapper = inspect(cls)
        return mapper.relationships.keys()

    def set_attrs(self, attrs: dict):
        """
        赋值
        :param attrs:
        :return:
        """
        for key, value in attrs.items():
            if hasattr(self, key) and key != "id":
                setattr(self, key, value)
